package com.xuexiang.xui_lib.component.progress.loading;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import com.xuexiang.xui_lib.ResourceTable;
import com.xuexiang.xui_lib.component.textview.marqueen.WeakHandler;

import java.io.IOException;

public class MiniLoadingDialog extends CommonDialog {
    /**
     * loading控件
     */
    private MiniLoadingView miniLoadingView;
    /**
     * 提示文字
     */
    private Text mTvTipMessage;

    private EventRunner runner = EventRunner.current();
    private WeakHandler handler = new WeakHandler(runner);
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    private long delayTime = 0;

    public MiniLoadingDialog(Context context) throws NotExistException, WrongTypeException, IOException {
        super(context);
        initView(context, "数据加载中...");
    }

    public MiniLoadingDialog(Context context, String tipMessage)
        throws NotExistException, WrongTypeException, IOException {
        super(context);
        initView(context, tipMessage);
    }

    private void initView(Context context, String tipMessage)
        throws NotExistException, WrongTypeException, IOException {
        Component component = LayoutScatter.getInstance(context)
            .parse(ResourceTable.Layout_xui_dialog_loading_mini, null, true);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ResourceTable.Graphic_background_black_radius);
        setTransparent(true);

        miniLoadingView = (MiniLoadingView) component.findComponentById(ResourceTable.Id_mini_loading_view);
        mTvTipMessage = (Text) component.findComponentById(ResourceTable.Id_tv_tip_message);
        mTvTipMessage.setText(tipMessage);
        setSize(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        setAlignment(LayoutAlignment.CENTER);
        setContentCustomComponent(component);
    }

    public MiniLoadingView getMiniLoadingView() {
        return miniLoadingView;
    }

    public Text getmTvTipMessage() {
        return mTvTipMessage;
    }

    public MiniLoadingDialog setDelayTime(long delayTime) {
        this.delayTime = delayTime;
        return this;
    }

    @Override
    public void hide() {
        super.hide();
        miniLoadingView.stop();
    }

    @Override
    public void show() {
        super.show();
        miniLoadingView.start();
        if (delayTime != 0) {
            handler.postDelayed(runnable, delayTime);
        }
    }
}
